import React from 'react';
import styles from './index.less';
import { message, Modal, Space, Tooltip } from 'antd';
import axios from 'axios';
import UA from 'ua-device';
import PcPlatform from './pc';
import H5Platform from './h5';
import { serverUriPrefix } from '../utils/const';
import { getItemList } from '../utils/url-parse';

class Home extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      platformType: null,  // Def: null, Val: h5/pc
      drawShow: false, // Def: false
      // 视频原始地址
      videoUrl: null,
      // 播放地址
      videoPlayUrl: null,
      // 播放线路
      parseLine: '',
      // 搜索渠道索引
      searchChannel: 2,
      // 播放线路
      videoLineList: [
        // 测试没问题的
        { name: '线路1(推荐)', subTitle: 'm3u8解析', url: 'https://jx.jsonplayer.com/player/?url=' },
        // { name: '线路1(推荐)', subTitle: 'bozrc', url: 'https://jx.bozrc.com:4433/player/?url=' },
        { name: '线路2(推荐)', subTitle: 'okjx', url: 'https://okjx.cc/?url=' },
        { name: '线路3', subTitle: 'm1907', url: 'https://z1.m1907.top/?jx=' },
        { name: '线路4', subTitle: 'playerjy', url: 'https://jx.playerjy.com/?url=' },
        { name: '线路5', subTitle: 'playm3u8', url: 'https://www.playm3u8.cn/jiexi.php?url=' },
        { name: '线路6', subTitle: '诺讯', url: 'https://www.nxflv.com/?url=' },
        { name: '线路7', subTitle: '盘古', url: 'https://www.pangujiexi.cc/jiexi.php?url=' },
        { name: '线路8', subTitle: 'RDHK', url: 'https://jx.rdhk.net/?v=' },
        { name: '线路9', subTitle: '17云', url: 'https://www.1717yun.com/jx/ty.php?url=' },
        { name: '线路10', subTitle: '8090', url: 'https://www.8090g.cn/?url=' },
        { name: '线路11', subTitle: 'ccyjjd', url: 'https://ckmov.ccyjjd.com/ckmov/?url=' },
        { name: '线路12', subTitle: 'jxla', url: 'https://api.jiexi.la/?url=' },
        { name: '线路13', subTitle: 'm3u8', url: 'https://jx.m3u8.tv/jiexi/?url=' },
        { name: '线路14', subTitle: '爱豆', url: 'https://jx.aidouer.net/?url=' },
        { name: '线路15', subTitle: 'CK', url: 'https://www.ckplayer.vip/jiexi/?url=' },
        { name: '线路16', subTitle: 'CHok', url: 'https://www.gai4.com/?url=' },
        { name: '线路17', subTitle: 'ckmov', url: 'https://www.ckmov.vip/api.php?url=' },
        { name: '线路18', subTitle: 'H8', url: 'https://www.h8jx.com/jiexi.php?url=' },
      ],
      // 渠道地址
      channelAddrList: [
        { name: '腾讯视频', url: 'https://v.qq.com/' },
        { name: '爱奇艺', url: 'https://www.iqiyi.com/' },
        { name: '优酷', url: 'https://www.youku.com/' },
        { name: 'B站', url: 'https://www.bilibili.com/' },
        { name: '芒果TV', url: 'https://www.mgtv.com/' },
        { name: '搜狐', url: 'https://tv.sohu.com/' },
        { name: '暴风影音', url: 'http://www.baofeng.com/' },
        { name: '搜狐视频', url: 'https://tv.sohu.com/' },
      ],
      // 当前剧集信息
      currVideoItem: null,
      // 电影名称
      videoName: null,
      // 视频渠道和剧集信息
      videoChannelList: [],
      // 是否显示播放地址标题旁边的高级按钮
      playAddressBtnShow: true, // Def: false
      // 搜索到的视频结果
      searchVideoResultList: [],
      // 视频搜索用于自动匹配的数据
      searchAutoCompleteDataList: [],
      // 搜索的关键词，用于回显
      searchKeyword: null,
      // 热门关键词
      hotKeywordList: [],
      // 是否正在搜索中
      isSearchLoading: false,
    };

    // 视频URL缓存(用户填写的)
    this.videoUrlCacheKey = 'videoUrlCacheKey';
    // 视频播放的URL缓存(解析后的)
    this.videoPlayUrlCacheKey = 'videoPlayUrlCacheKey';
    // 视频每集数据
    this.searchVideoResultListCacheKey = 'searchVideoResultListCacheKey';
    // 当前播放的视频名称
    this.videoNameCacheKey = 'videoNameCacheKey';
    // 当前播放的线路
    this.videoLineCacheKey = 'videoLineCacheKey';
    // 搜索的内容
    this.searchKeywordCacheKey = 'searchKeywordCacheKey';
  }

  componentDidMount() {
    // ============ 正式代码 ============
    this.ipCheck();

    this.handleResize();
    window.addEventListener('resize', this.handleResize);

    // 搜索热门关键词
    this.searchHotKeyword();

    // 防止setState事件合并
    setTimeout(() => this.initCache(), 0);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  ipCheck = () => {
    axios.get(`${serverUriPrefix}/api/check`)
      .then(resp => {
        const body = resp.data;
        const { code, msg, data } = body;
        if(data) {
          document.body.innerHTML = '';
          Modal.warning({
            title: '系统提示',
            icon: '',
            content: <span>涉嫌恶意操作封禁，本系统将不再为您服务<br/>如有疑问，请联系管理员！</span>,
            onOk() {

            },
          });

          this.setState({ drawShow: false })
          localStorage.removeItem(this.videoUrlCacheKey);
          localStorage.removeItem(this.videoPlayUrlCacheKey );
          localStorage.removeItem(this.searchVideoResultListCacheKey);
          localStorage.removeItem(this.videoNameCacheKey);
          localStorage.removeItem(this.videoLineCacheKey);
          localStorage.removeItem(this.searchKeywordCacheKey);
        }
      }).catch(e => {

    });
  }

  searchHotKeyword = () => {
    axios.get(`${serverUriPrefix}/api/hotKeyword`)
      .then(resp => {
        const body = resp.data;
        const { code, msg, data } = body;
        if(code === 'success') {
          this.setState({ hotKeywordList: data })
        }
      }).catch(e => {

    });
  }

  handleResize = () => {
    const ua = new UA(navigator.userAgent);
    if (['iOS', 'Android'].some(device => device === ua.os.name)) {
      this.setState({ platformType: 'h5' });
    } else {
      this.setState({ platformType: 'pc' });
    }
  };

  /**
   * 初始化缓存
   */
  initCache = () => {
    // 缓存的电影播放地址
    const videoPlayUrlCache = localStorage.getItem(this.videoPlayUrlCacheKey);
    let videoPlayUrl = null;
    if (videoPlayUrlCache && videoPlayUrlCache !== 'null') {
      videoPlayUrl = videoPlayUrlCache;
    }
    this.setState({ drawShow: !!!videoPlayUrl, videoPlayUrl });

    // 缓存电影的渠道地址(用户复制来的)
    const videoUrlCache = localStorage.getItem(this.videoUrlCacheKey);
    if (videoUrlCache && videoUrlCache !== 'null') {
      this.setState({ videoUrl: videoUrlCache });
    }

    // 视频名称
    const videoName = localStorage.getItem(this.videoNameCacheKey);
    if (videoName && videoName !== 'null') {
      this.setState({ videoName });
    }

    // 缓存的电影每集信息
    const videoItemListCacheStr = localStorage.getItem(this.searchVideoResultListCacheKey);
    if (videoItemListCacheStr && videoItemListCacheStr.length > 0) {
      const searchVideoResultList = JSON.parse(videoItemListCacheStr);
      this.setState({ searchVideoResultList });

      // 如果有电影名称，把渠道信息也计算出来
      if (videoName) {
        const videoChannel = searchVideoResultList.find(item => item.title === videoName) || {};
        this.setState({ videoChannelList: videoChannel.channelList });
      }
    }

    // 当前线路
    const parseLine = localStorage.getItem(this.videoLineCacheKey);
    if (parseLine && parseLine !== 'null') {
      this.setState({ parseLine });
    } else {
      this.setState({ parseLine: this.state.videoLineList[0].url });
    }

    // 搜索的关键词
    const searchKeyword = localStorage.getItem(this.searchKeywordCacheKey);
    if (searchKeyword && searchKeyword !== 'null') {
      this.setState({ searchKeyword });
    }

    // 缓存加载完后，若播放则定位到浏览器最底部
    this.toBrowserBottom();
  };

  /**
   * 搜索到的视频结果名称被点击
   * @param videoItem
   */
  onVideoTitleChange = (videoItem) => {
    const { title, channelList } = videoItem || {};
    this.setState({ videoChannelList: null });
    setTimeout(() => {
      this.setState({ videoName: title, videoChannelList: channelList });
      // 视频名称缓存起来
      localStorage.setItem(this.videoNameCacheKey, title);
      // 跳转到浏览器最底部
      this.toBrowserBottom();
    }, 0);
  };

  /**
   * 点击某一集
   * @param videoItem 剧集对象 {name, url, desc}
   */
  onVideoItemChange = (videoItem) => {
    this.setState({ videoPlayUrl: null, currVideoItem: videoItem });
    setTimeout(() => {
      const videoPlayUrl = this.getVideoPlayUrl(videoItem.url);
      this.setState({
        videoPlayUrl: videoPlayUrl,
        videoUrl: videoItem.url,
      });
      localStorage.setItem(this.videoUrlCacheKey, videoItem.url);
      // 当前播放的URL存起来
      localStorage.setItem(this.videoPlayUrlCacheKey, videoPlayUrl);
      // 当前线路
      localStorage.setItem(this.videoLineCacheKey, this.state.parseLine);
      // 跳转到浏览器最底部
      this.toBrowserBottom();
    });
  };

  /**
   * 线路变更
   * @param line
   */
  onVideoLineChange = line => {
    this.setState({ parseLine: line });

    setTimeout(() => {
      const { currVideoItem } = this.state;
      currVideoItem && this.onVideoItemChange(currVideoItem);
    }, 0);
  };

  /**
   * 直解原链
   */
  directParseVideo = async () => {
    const { videoUrl } = this.state;
    try {
      const ua = new URL(videoUrl);
      // 直接解析
      this.setState({ videoPlayUrl: null, videoName: null });
      setTimeout(() => {
        this.setState({ videoPlayUrl: this.getVideoPlayUrl(videoUrl) });
        // 直链解析，尝试获取集数(实验功能)
        this.directParseVideoItemList(ua.href);
      }, 0);
      // 视频地址
      localStorage.setItem(this.videoUrlCacheKey, videoUrl);
    } catch (e) {
      console.error(e);
      message.error('解析失败，请核查URL', 5);
    }
  };

  /**
   * 直链解析时，尝试获取每集信息(实验性)
   * @param url
   * @return {Promise<unknown>}
   */
  directParseVideoItemList = async (url) => {
    getItemList(url)
      .then(resp => {
        this.setState({ videoChannelList: [], videoName: null });

        setTimeout(() => {
          // console.log('parse resp ', resp);
          const { data, type } = resp || {};
          if (type === 0 && data) {
            // this.setState({ videoChannelList: data.channelList, videoName: data.title });
            this.onVideoTitleChange(data);

            this.setState({ searchVideoResultList: [data] });
            localStorage.setItem(this.searchVideoResultListCacheKey, JSON.stringify([data]));
          }
        });
      }).catch(e => {
      this.setState({ videoName: null });
    });
  };

  /**
   * 获取视频播放的URL
   * @param videoUrl
   * @return {string}
   */
  getVideoPlayUrl = (videoUrl) => {
    const { parseLine, videoLineList } = this.state;
    const videoLine = parseLine || videoLineList[0].url;
    const videoPlayUrl = `${videoLine}${videoUrl}`;
    // 当前播放地址
    localStorage.setItem(this.videoPlayUrlCacheKey, videoPlayUrl);
    return videoPlayUrl;
  };

  /**
   * 跳转到浏览器最底部
   */
  toBrowserBottom = () => {
    let anchorElement = document.getElementById('endAnchorPointId');
    if (anchorElement) {
      anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
    // 聚焦
    this.iframeRef?.focus();
  };

  /**
   * 根据关键词搜索key
   */
  onSearchVideo = () => {
    const { searchKeyword } = this.state;
    if (searchKeyword) {
      axios.get(`${serverUriPrefix}/searchProxy/api/search_prompt?k=${encodeURIComponent(searchKeyword)}`)
        .then(resp => {
          const body = resp.data;
          const searchAutoCompleteDataList = [];
          body?.forEach(item => {
            searchAutoCompleteDataList.push({ label: item.name, value: item.name });
          });
          this.setState({ searchAutoCompleteDataList });
        }).catch(e => {
        this.setState({ searchAutoCompleteDataList: [] });
      });
    }
  };

  /**
   * 搜索视频详情
   */
  onSearchVideoItemList = () => {
    const { searchKeyword, searchChannel } = this.state;
    if (searchKeyword) {
      // 链接搜索判断
      if (searchKeyword?.trim().startsWith('http')) {
        message.warn('内容疑似链接，已为您切换搜索模式', 5);
        this.setState({ playAddressBtnShow: false, videoUrl: searchKeyword });
        return;
      }
      this.setState({ isSearchLoading: true });

      axios.get(`${serverUriPrefix}/api/parse?keyword=${searchKeyword}&searchChannel=${searchChannel}`)
        .then(resp => {
          this.setState({ isSearchLoading: false });

          const body = resp.data;
          const { code, msg, data } = body;
          if (code === 'success') {
            // [{"title":"奔跑吧第六季","channelList":[{"channelName":"爱奇艺","videoItemList":[{"name":"20220731","url":"https://www.iqiyi.com/v_1m5gylxxqu0.html?vfm=m_312_shsp&fv=9bdf85be5ffe0f89"},{"name":"20220729","url":"https://www.iqiyi.com/v_z6ieyqwsqs.html?vfm=m_312_shsp&fv=9bdf85be5ffe0f89"}]},{"channelName":"优酷","videoItemList":[{"name":"20220731","url":"https://v.youku.com/v_show/id_XNTg4OTk4MTEzNg==.html?tpa=dW5pb25faWQ9MTAzNjUzXzEwMDAwMV8wMV8wMQ&x&refer=sohushipin&from=souhushipin"},{"name":"20220730","url":"https://v.youku.com/v_show/id_XNTg5MDg5MjU2OA==.html?tpa=dW5pb25faWQ9MTAzNjUzXzEwMDAwMV8wMV8wMQ&x&refer=sohushipin&from=souhushipin"}]},{"channelName":"腾讯","videoItemList":[{"name":"20220729","url":"https://v.qq.com/x/cover/mzc00200zb1b9uj.html?ptag=sohu.variety"},{"name":"20220722","url":"https://v.qq.com/x/cover/mzc00200dihsjxu.html?ptag=sohu.variety"}]}]},{"title":"奔跑吧第五季","channelList":[{"channelName":"优酷","videoItemList":[{"name":"20210718","url":"https://v.youku.com/v_show/id_XNTE2MDcyMDU0OA==.html?tpa=dW5pb25faWQ9MTAzNjUzXzEwMDAwMV8wMV8wMQ&x&refer=sohushipin&from=souhushipin"}]},{"channelName":"爱奇艺","videoItemList":[{"name":"20210716","url":"https://www.iqiyi.com/v_cnn2myz5q8.html?vfm=m_312_shsp&fv=9bdf85be5ffe0f89"}]},{"channelName":"腾讯","videoItemList":[{"name":"20210716","url":"https://v.qq.com/x/cover/mzc0020091tnm2g.html?ptag=sohu.variety"}]}]}]
            this.setState({ searchVideoResultList: data });
            localStorage.setItem(this.searchVideoResultListCacheKey, JSON.stringify(data));
            if (data.length === 0) {
              message.warn('未搜索到数据');
            }
          } else {
            message.error(msg);
            this.setState({ searchVideoResultList: [] });
          }
        }).catch(e => {
        this.setState({ searchVideoResultList: [] });
        this.setState({ isSearchLoading: false });
        message.error('搜索超时，请稍候再试');
      });
      localStorage.setItem(this.searchKeywordCacheKey, searchKeyword);
    } else {
      message.warn('请输入视频名称');
    }
  };

  /**
   * 选择集数
   * @param typeNum 类型数值，-1: 上一集，1：下一集
   */
  selectVideoItem = (typeNum) => {
    // 检索数据，这里直接检索多个渠道的数据，通过记录的URL匹配
    const { videoChannelList, videoUrl } = this.state;
    if (videoUrl && videoChannelList?.length > 0) {
      videoChannelList.forEach(channel => {
        // 剧集信息
        const videoItemList = channel.videoItemList || [];
        for (let i = 0; i < videoItemList.length; ++i) {
          const videoItem = videoItemList[i];
          if (videoItem.url === videoUrl) {
            const newIndex = i + typeNum;
            if (newIndex < 0) {
              message.warn('已是第一集');
            } else if (newIndex >= videoItemList.length) {
              message.warn('已是最后一集');
            } else {
              this.onVideoItemChange(videoItemList[newIndex]);
            }
          }
        }
      });
    }
  };

  render() {
    const { drawShow, videoPlayUrl, platformType } = this.state;
    return (
      <div className={styles.wrap}>
        {
          videoPlayUrl && <iframe
            src={videoPlayUrl}
            className={styles.video}
            frameBorder={'none'}
            scrolling='none'
            allowFullScreen={true}
            ref={ref => this.iframeRef = ref}
            style={{
              transition: 'all 0.3s',
              width: (platformType === 'pc' && drawShow) ? 'calc(100vw - 640px)' : '100vw',
              height: '100vh',
            }}
          />
        }

        {/* 占位用的视频窗口 */}
        {!videoPlayUrl && <video
          controls
          className={styles.video}
          style={{
            transition: 'all 0.3s',
            width: (platformType === 'pc' && drawShow) ? 'calc(100vw - 640px)' : '100vw',
            height: '100vh',
          }} />}

        {/* PC平台 */}
        {platformType === 'pc' && <PcPlatform
          {...this.state}
          onUpdateState={(obj) => this.setState(obj)}
          onCloseDraw={() => {
            this.setState({ drawShow: false });
            // 浏览器拉到底
            setTimeout(() => this.toBrowserBottom(), 200);
          }}
          onSearchVideo={() => this.onSearchVideo()}
          onSearchVideoItemList={() => this.onSearchVideoItemList()}
          onDirectParseVideo={() => this.directParseVideo()}
          onVideoTitleChange={(videoItem) => this.onVideoTitleChange(videoItem)}
          onVideoItemChange={(videoItem) => this.onVideoItemChange(videoItem)}
          onVideoLineChange={line => this.onVideoLineChange(line)}
        />}

        {/*h5平台，请注意：platformType 可能为 null*/}
        {platformType === 'h5' && <H5Platform
          {...this.state}
          onUpdateState={(obj) => this.setState(obj)}
          onCloseDraw={() => {
            this.setState({ drawShow: false });
            // 浏览器拉到底
            setTimeout(() => this.toBrowserBottom(), 200);
          }}
          onSearchVideo={() => this.onSearchVideo()}
          onSearchVideoItemList={() => this.onSearchVideoItemList()}
          onDirectParseVideo={() => this.directParseVideo()}
          onVideoTitleChange={(videoItem) => this.onVideoTitleChange(videoItem)}
          onVideoItemChange={(videoItem) => this.onVideoItemChange(videoItem)}
          onVideoLineChange={line => this.onVideoLineChange(line)}
        />}

        <div style={{ display: drawShow ? 'none' : 'block' }} className={styles.drawerShow}>
          <div className={styles.menu}>
            <Tooltip title={'上一集'}>
              <div className={styles.img1} onClick={() => this.selectVideoItem(-1)} />
            </Tooltip>
            <Tooltip title={'刷新'}>
              <div className={styles.img2} onClick={() => location.reload()} />
            </Tooltip>
            <Tooltip title={'下一集'}>
              <div className={styles.img3} onClick={() => this.selectVideoItem(1)} />
            </Tooltip>
            <Tooltip title={'解析器'}>
              <div className={styles.img4} onClick={() => this.setState({ drawShow: true })} />
            </Tooltip>
          </div>
        </div>

        {/* 锚点用的，目的是跳转到浏览器的最底下 */}
        <div id={'endAnchorPointId'} style={{ position: 'absolute' }} />
      </div>
    );
  }
}

export default Home;